package com.ihr360.payroll.model.meta;

import com.ihr360.commons.entity.metadata.IPropertyMeta;
import com.ihr360.commons.lang.StringUtils;
import com.ihr360.commons.model.meta.AbstractPropertyMeta;

import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/** 属性元信息 */
@Entity
public class PropertyMeta  extends AbstractPropertyMeta implements IPropertyMeta<Long,EntityMeta>{
    private static final long serialVersionUID = 3184051459377435446L;

    /** 所属实体元 */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    private EntityMeta entityMeta;

    @ElementCollection
    private Set<String> businesses = new HashSet<>();
    @Override
    public EntityMeta getEntityMeta() {
        return entityMeta;
    }

    @Override
    public void setEntityMeta(EntityMeta entityMeta) {
        this.entityMeta = entityMeta;
    }

    @Override
    public boolean isSimpleType(){
        if(null != type) {
            return type.getPackage().getName().startsWith("java.");
        }
        return false;
    }

    @Override
    public String getTypeName(){
        if(null != type) {
            if(Number.class.isAssignableFrom(type)){
                return "number";
            } else if(Date.class.isAssignableFrom(type)) {
                return "date";
            }
            return StringUtils.uncapitalize(type.getSimpleName());
        }
        return null;
    }

    @Override
    public Set<String> getBusinesses() {
        if(this.businesses.size() > 0){
            Set<String> _businesses = new HashSet<>();
            StringBuilder sbuilder = new StringBuilder();
            for(Iterator<String> iterator = this.businesses.iterator(); iterator.hasNext();){
                String str = iterator.next();
                sbuilder.append(str);
                sbuilder.append(",");
            }
            String str = sbuilder.toString();
            _businesses.add(str.substring(0,str.length()-1));
            return _businesses;
        }
        return businesses;
    }

    public void setBusinesses(Set<String> businesses) {
        this.businesses = businesses;
    }
}